package org.ru.mse10.cvis.web.components;

import java.io.IOException;

import javax.faces.component.FacesComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.naming.NamingException;

import org.ru.mse10.cvis.service.CodelistService;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class HtmlCodelistValueOutput.
 */
@FacesComponent(value = "HtmlCodelistValueOutput")
public class HtmlCodelistValueOutput extends UIOutput {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.component.UIComponentBase#encodeBegin(javax.faces.context
	 * .FacesContext)
	 */
	@Override
	public void encodeBegin(FacesContext context) throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("span", this);
		CodelistService service;
		try {
			String styleAttr = (String) this.getAttributes().get("style");
			String styleClassAttr = (String) this.getAttributes().get(
					"styleClass");
			if (!CommonUtil.isEmpty(styleAttr)) {
				writer.writeAttribute("style", styleAttr, null);
			}
			if (!CommonUtil.isEmpty(styleClassAttr)) {
				writer.writeAttribute("class", styleClassAttr, null);
			}
			service = CommonUtil.lookupService(CodelistService.class);
			String value = service.getCodelistValue((String) this
					.getAttributes().get("cl"), String.valueOf(this
					.getAttributes().get("clValue")), (String) this
					.getAttributes().get("lang"));
			if (CommonUtil.isEmpty(value)) {
				String noResultValue = (String) this.getAttributes().get(
						"noResultValue");
				writer.write(CommonUtil.isEmpty(noResultValue) ? ""
						: noResultValue);
			} else {
				writer.write(value);
			}
			writer.endElement("span");
			writer.flush();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.component.UIComponentBase#encodeEnd(javax.faces.context.
	 * FacesContext)
	 */
	@Override
	public void encodeEnd(FacesContext context) throws IOException {
		return;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.component.UIComponentBase#decode(javax.faces.context.FacesContext
	 * )
	 */
	@Override
	public void decode(FacesContext context) {
		return;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.component.UIOutput#getFamily()
	 */
	@Override
	public String getFamily() {
		return "simple.Label";
	}

}
